<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click.stop="handleSave">新 建</el-button>

        <!-- <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permissionList.delBtn"
          @click="handleDelete"
          >删 除
        </el-button> -->
      </template>
      <!-- <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.terminal_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.terminal_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="scope" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click.stop="handleView(scope.row, scope.index)">查 看</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click.stop="handleEdit(scope.row, scope.index)">修 改</el-button>
        <!-- <el-button icon="el-icon-key" size="small" type="text" v-if="permissionList.delBtn" @click.stop="rowDel(scope.row)">解 绑</el-button> 需求-->
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
    <!-- 新建 -->
    <el-dialog
      :title="terminalDialog.text"
      top="1%"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="terminalDialog.visible"
      v-if="terminalDialog.visible"
      :before-close="terminalDialogHandleClose"
    >
      <equipmentDialog  ref='terminalDialog' :terminalDialog="terminalDialog" :rptNoList="rptNoList" :rpiNoList="rpiNoList"  :terminalDForm="terminalDForm"/>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => { terminalDialog.visible = false; this.$refs['terminalDialog'].initEmpty();}">取 消</el-button>
        <el-button type="primary" v-preventClick @click="terminalDialogSubmit" v-if="!terminalDialog.disabled">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form :model="towPwdForm" ref="towPwdForm" label-width="0" class="demo-ruleForm">
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            { required: true,message: '二级密码不能为空', trigger: ['change','blur']},
            { pattern: /^[0-9]{6}$/, message: '二级密码由6位数字组成', trigger: ['change','blur']}
          ]"
          >
          <el-input show-password v-model.number="towPwdForm.towPwd" autocomplete="off" placeholder="输入二级密码"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
  // addTerminal,
  // editTerminal,
import {
  getList,
  getDetail,
  getRptNo,
  getrpiNo,
  detailEq,
  getrpstNo,
  getstoreNo,
  equipmentSubmitEq,
  getRpsNo,
  getrpmNo
} from "@/api/rb-service/terminal/terminal";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import equipmentDialog from "./equipmentDialog";
import { userHasInfo } from "@/api/rb-service/forgetPassword/forgetPassword";
import md5 from 'js-md5';
import { remove } from "@/api/rb-service/posinfo/terminalStore/store";

export default {
   components: {
    equipmentDialog
  },
  data() {
    return {
      form: {},
      query: {},
      search: {},
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        addBtn: false,//取消表格 新建/添加
        labelWidth:100,
        editBtn:false,
        viewBtn:false,
        delBtn:false,
        viewTitle:'修 改',
        column: [
          {
            label: "机构编号",
            prop: "serNo",
            type: "input",
            display:false,
            minWidth:140,
            overHidden: true
          },
          {
            label: "机构名称",
            prop: "serCompany",
            type: "input",
            display:false,
            overHidden: true,
            minWidth:180
          },
          {
            label: "直属代理编号",
            prop: "serviceNo",
            type: "input",
            minWidth:140,
            display:false,
            overHidden: true
          },
          {
            label: "直属代理名称",
            prop: "serviceName",
            type: "input",
            minWidth:180,
            display:false,
            overHidden: true
          },
          {
            label: "设备简称",
            prop: "rtName",
            type: "input",
            //sortable: true,
            display:false,
            overHidden: true,
          },
          {
            label: "类型",
            prop: "rptName",
            type: "input",
            //sortable: true,
            display:false,
            overHidden: true,
          },
          {
            label: "类型",
            prop: "rptNo",
            type: "select",
            //sortable: true,
            search: true,
            hide:true,
            display:false,
            rules: [
              {
                required: true,
                message: "请选择类型",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rptName',
              value: 'rptNo',
              desc:'rptNo'
            },
            filterable:true,
            searchOrder:1,
            dicData: [],
            change: (value) => {
              if (value) {
                // 获取供应商
                this.search.rpsNo = '';
                this.rpsNoList = [];
                this.search.rpmNo = '';
                this.rpmNoList = [];
                if (value.value) {
                  this.apiRpsNoList(value.value);//供应商
                }
              }
            },
            overHidden: true,
          },
          {
            label: "供应商",
            prop: "rpsName",
            type: "input",
            //sortable: true,
            display:false,
            overHidden: true,
            minWidth:140
          },
           {
            label: "供应商",
            prop: "rpsNo",
            type: "select",
            //sortable: true,
            search: true,
            hide:true,
            filterable:true,
            display:false,
            overHidden: true,
            rules: [
              {
                required: true,
                message: "请选择供应商",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc:'rpsNo'
            },
            // dicUrl: `/api/rb-service/service/terminal/terminal/supList?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            dicData: [],
            searchOrder:2,
            change: (value) => {
              if (value) {
                // 获取型号
                this.search.rpmNo = '';
                this.rpmNoList = [];
                if (value.value) {
                  this.apiModelListList(value.value);//型号
                }
              }
            }
          },
          {
            label: "型号",
            prop: "rpmName",
            type: "input",
            //sortable: true,
            display:false,
            overHidden: true,
            minWidth:140
          },
          {
            label: "型号",
            prop: "rpmNo",
            type: "select",
            //sortable: true,
            search: true,
            hide:true,
            display:false,
            rules: [
              {
                required: true,
                message: "请输入型号",
                trigger: "blur",
              },
            ],
            filterable:true,
            searchOrder:3,
            props: {
              label: 'rpmName',
              value: 'rpmNo',
              desc:'rpmNo'
            },
            dicData: [],
            // dicUrl: `/api/rb-service/service/terminal/terminal/modelListV2?current=-1&size=-1`,
            // dicFormatter:(data)=>{
            //   return data.data.records
            // },
            overHidden: true
          },
          {
            label: "商户",
            prop: "rpiName",
            type: "input",
            width: 200,
            display:false,
          },
          {
            label: "商户",
            prop: "rpiNo",
            type: "select",
            //sortable: true,
            search: true,
            hide:true,
            filterable:true,
            display:false,
            rules: [
              {
                required: true,
                message: "请选择商户",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpiName',
              value: 'rpiNo',
              desc: 'rpiNo'
            },
            searchOrder:4,
            dicData: [],
            overHidden: true,
          },
          {
            label: "门店",
            prop: "storeNo",
            type: "select",
            //sortable: true,
            hide:true,
            filterable:true,
            search: false,
            rules: [
              {
                required: true,
                message: "请选择门店",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpsName',
              value: 'rpsNo',
              desc:'rpsNo'
            },
            searchOrder:5,
            dicUrl: `/api/rb-service/service/posStore/pos_store/listV2?current=-1&size=-1`,
            dicFormatter:(data)=>{
              return data.data.records
            },
            // dicData: [],
            // change: (value) => {
            //   if (value) {
            //     if(value.value){
            //       getrpstNo(-1,-1,{rpsNo:value.value}).then((res)=>{
            //         this.rpstNoList = res.data.data.records;
            //         const column = this.findObject(this.option.column, "rpstNo");
            //         column.dicData = this.rpstNoList;
            //       })
            //     }
            //   }
            // },
            overHidden: true,
          },
          {
            label: "收银员",
            prop: "rpstNo",
            type: "select",
            //sortable: true,
            hide:true,
            search: false,
            searchLabelWidth: 94,
            rules: [
              {
                required: true,
                message: "请选择收银员",
                trigger: "blur",
              },
            ],
            props: {
              label: 'rpstName',
              value: 'rpstNo',
              desc:'rpstNo'
            },
            dicUrl: `/api/rb-service/service/posStaff/pos_staff/listV2?current=-1&size=-1`,
            dicFormatter:(data)=>{
              return data.data.records
            },
            // dicData: [],
            searchOrder:6,
            filterable:true,
            overHidden: true,
          },
          {
            label: "设备编号",
            prop: "rsSn",
            type: "input",
            //sortable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入设备编号",
                trigger: "blur",
              },
            ],
            overHidden: true,
            minWidth:100
          },
          // {
          //   label: "扩展属性",
          //   prop: "rtPara",
          //   type: "input",
          //   //sortable: true,
          // },
          // {
          //   label: "是否启用",
          //   prop: "isOn",
          //   type: "switch",
          //   //sortable: true,
          //   dicUrl: "/api/blade-system/dict/dictionary?code=is_on",
          //   props: {
          //     label: "dictValue",
          //     value: "dictKey",
          //   },
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入是否启用",
          //       trigger: "blur",
          //     },
          //   ],
          // },
        ]
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-service/service/terminal/terminal/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
      terminalDialog:{
        disabled:false,
        visible:false,
        type:'add',
        text:'新建'
      },//表格右侧操作add,edit,view
      terminalDForm:{},//设备表单
      rptNoList:[],//类型
      rpsNoList:[],//供应商名称
      rpmNoList:[],//型号
      rpiNoList:[],//商户号
      storeNoList:[],//门店
      rpstNoList:[],//收银员
      hasPayPwd:false,
      twoPwdShow:false,
      towPwdForm:{
        towPwd:'',
        rpiNo:"",
        rsSn:""
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.terminal_add, false),
        viewBtn: this.vaildData(this.permission.terminal_view, false),
        //delBtn: this.vaildData(this.permission.terminal_delete, false),
        editBtn: this.vaildData(this.permission.terminal_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  watch:{},
  created(){
     this.initRequest()
  },
  methods: {
    // 二级密码 关闭回调
    handleCloseTwoPwd(done){
      this.towPwdForm.towPwd="";
      done()
    },
    // 二级密码 确定
    twoPwdSubmit(){
      let that = this;
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          let param={
            payPwd:md5(that.towPwdForm.towPwd+''),
            rpiNo:that.towPwdForm.rpiNo,
            rsSn:that.towPwdForm.rsSn
          }
          remove(param).then((res) => {
            that.onLoad(this.page);
            that.$message({
              type: "success",
              message: res.data.msg
            });
            that.$refs.crud.toggleSelection();
            that.twoPwdShow = false;
            that.towPwdForm.towPwd="";
          });
        } else {
          return false;
         }
      });
    },
    // 是否 有二级密码
    getUserHasInfo(){
      userHasInfo().then(res =>{
        this.hasPayPwd = res.data.data.hasPayPwd;
      }, error => {
        window.console.log(error);
      })
    },
    // 跳转用户信息页面
    toUserInfo(){
      this.$confirm('请您先设置二级密码，再操作！', '提示', {
        confirmButtonText: '确定',
        showCancelButton:false,
        type: 'warning'
      }).then(() => {
        this.$router.push({ path: '/info/index', query: { index: 2 }})
      })
    },
    // 新建
    handleSave() {
      this.terminalDialog.visible = true;
      this.terminalDialog.type = 'add';
      this.terminalDialog.text = "新建设备";
      this.terminalDialog.disabled=false;
    },
    // 编辑
    handleEdit(row) {
      // this.basicDetail(row);
      this.getDetailEq(row.id,'edit')
    },
    // 查看
    handleView(row) {
      this.getDetailEq(row.id,'view')
    },
    // 详情
    getDetailEq(id,type){
       detailEq(id).then(res=>{
          this.terminalDForm=JSON.parse(JSON.stringify(res.data.data));
          this.terminalDialog.visible = true;
          if(type=='edit'){
            this.terminalDialog.type = 'edit';
            this.terminalDialog.text = "修改设备";
            this.terminalDialog.disabled=false;
          }else if(type=='view'){
            this.terminalDialog.type = 'view';
            this.terminalDialog.text = "查看";
            this.terminalDialog.disabled=true;
          }
      })
    },
    rowDel(row) {
      if(!this.hasPayPwd){
        this.toUserInfo()
      } else {
        this.towPwdForm.rpiNo = row.rpiNo;
        this.towPwdForm.rsSn = row.rsSn;
        
        this.twoPwdShow = true;
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      // if(!this.hasPayPwd){
      //   this.toUserInfo();
      // } else {
      //   this.towPwdForm.ids = this.ids;
      //   this.twoPwdShow = true;
      // }
      let that = this;
      remove(this.ids).then(() => {
        that.onLoad(this.page);
        that.$message({
          type: "success",
          message: "操作成功!"
        });
        // that.$refs.crud.toggleSelection();
        that.twoPwdShow = false;
        that.towPwdForm.towPwd="";
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        Object.assign(params, this.query,{eqType:0})
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rtName=${this.search.rtName}`;
      exQuery += `&rtNo=${this.search.rtNo}`;
      exQuery += `&rpsNo=${this.search.rpsNo}`;
      exQuery += `&rptNo=${this.search.rptNo}`;
      exQuery += `&rpmNo=${this.search.rpmNo}`;
      exQuery += `&rsSn=${this.search.rsSn}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&storeNo=${this.search.storeNo}`;
      exQuery += `&rpstNo=${this.search.rpstNo}`;
      exQuery += `&rtPara=${this.search.rtPara}`;
      exQuery += `&isOn=${this.search.isOn}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-service/service/terminal/terminal/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-service/service/terminal/terminal/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
    // 设备---新建弹框 关闭前回调
    terminalDialogHandleClose(done) {
      this.$refs['terminalDialog'].initEmpty();
      done();
    },
    // 获取 类型名称
    requestRptNo(){
      getRptNo(-1,-1,{eqType:0}).then((res)=>{
        this.rptNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rptNo");
        column.dicData = this.rptNoList;
      })
    },
    // 获取 商户
    requestrpiNo(){
      getrpiNo(-1,-1).then((res)=>{
        this.rpiNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpiNo");
        column.dicData = this.rpiNoList;
      })
    },
    // 获取 门店名称
    rpiNoListChange(rpiNo = "") {
      let param ={};
      if(rpiNo){
        param.rpiNo = rpiNo;
      }
      getstoreNo(-1, -1, param).then((res) => {
        this.storeNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "storeNo");
        column.dicData = this.storeNoList;
        this.$forceUpdate();
      })
    },
    // 获取 收银员名称
    apiRpstList(rpsNo = "") {
      let param ={};
      if(rpsNo){
        param.rpsNo = rpsNo;
      }
      getrpstNo(-1, -1, param).then((res) => {
        this.rpstNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpstNo");
        column.dicData = this.rpstNoList;
        this.$forceUpdate();
      })
    },
    initRequest(){
      this.requestRptNo();//获取 类型

      this.apiRpsNoList();// 获取 供应商

      this.apiModelListList();// 获取 型号

      this.requestrpiNo();//获取 商户
      
      this.getUserHasInfo();//是否 有二级密码
    },
    // 获取 供应商
    apiRpsNoList(rptNo = "") {
      let param ={};
      if(rptNo){
        param.rptNo = rptNo;
      }
      getRpsNo(-1,-1,param).then((res)=>{
        this.rpsNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpsNo");
        column.dicData = this.rpsNoList;
      })
    },
    // 获取型号
    apiModelListList(rpsNo = "") {
      let param ={};
      if(rpsNo){
        param.rpsNo = rpsNo ;
      }
      getrpmNo(-1, -1, param).then((res) => {
        this.rpmNoList = res.data.data.records;
        const column = this.findObject(this.option.column, "rpmNo");
        column.dicData = this.rpmNoList;
        this.$forceUpdate();
      })
    },
    async submitEq(param){
      await equipmentSubmitEq(param).then(() => {
        this.onLoad(this.page);
        this.$refs['terminalDialog'].initEmpty();

        this.$message({
          type: "success",
          message: "操作成功!",
        });
              // message: res.data.message,

        // setTimeout(() => {
          this.terminalDialog.visible = false;
        // }, 1500);
      },
      (error) => {
        window.console.log(error);
      }
    );
    },
     // 设备---新建弹框提交
     terminalDialogSubmit(){
        /**
         * add  新建
         * edit 修改
         * view 查看详情
         */
       if (this.terminalDialog.type !== 'view') {

        this.$refs['terminalDialog'].$refs['terminalDialogForm'].validate((valid) => {
          let TERMINAL_DIALOG=this.$refs['terminalDialog'];
          let values=[];
          if (valid) {
            if(TERMINAL_DIALOG.transferdataVal.length>0){
              TERMINAL_DIALOG.transferdataVal.forEach((item1)=>{
                let rtNo = TERMINAL_DIALOG.transferdata.find(item2 => item2.rtNo == item1);
                if(rtNo){
                  values.push(rtNo)
                }
              })
            }

            // add---str
            let rtPara = {}
            TERMINAL_DIALOG.terminalDialogForm.rtParaList.map(itm=>{
              rtPara[itm.key]=itm.val;
            })
            TERMINAL_DIALOG.terminalDialogForm.rtPara=JSON.stringify(rtPara)
            // add---edit

            let param = {
              // ...TERMINAL_DIALOG.terminalDialogForm,//1
              eqType:0,
              id: TERMINAL_DIALOG.terminalDialogForm.id,
              rpiNo:  TERMINAL_DIALOG.terminalDialogForm.rpiNo,
              rpmNo:  TERMINAL_DIALOG.terminalDialogForm.rpmNo,
              rpsNo:  TERMINAL_DIALOG.terminalDialogForm.rpsNo,
              rptNo:  TERMINAL_DIALOG.terminalDialogForm.rptNo,
              rsSn:  TERMINAL_DIALOG.terminalDialogForm.rsSn,
              rtName:  TERMINAL_DIALOG.terminalDialogForm.rtName,
              rtNo:  TERMINAL_DIALOG.terminalDialogForm.rtNo,
              rtPara:  TERMINAL_DIALOG.terminalDialogForm.rtPara,
              dto:TERMINAL_DIALOG.storeAndMerchantTreeSelect,//2
              values:values//3
            }
            if(param.rptNo =='17'){
              param.copy = TERMINAL_DIALOG.terminalDialogForm.copy;//份数
              param.joint = TERMINAL_DIALOG.terminalDialogForm.joint;//联数
            }
            this.submitEq(param)
          }
        });
      }
    },
  }
};
</script>

<style>
</style>
